package com.hontech.bread.store

import com.hontech.bread.R
import com.hontech.bread.utils.currentTimestamp
import com.hontech.bread.utils.runCPU
import com.hontech.bread.utils.stringById

class StoreLog(
    val createTimestamp: Long,
    val msg: String
) {

    companion object {

        const val TAG_ERROR = 1
        const val TAG_WARNING = 2
        const val TAG_INFO = 3
        const val TAG_DEBUG = 4
        const val TAG_TRACE = 5

        const val TB_NAME = "tb_store_log"

        const val CREATE_SQL = "CREATE TABLE IF NOT EXISTS $TB_NAME (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "create_timestamp INTEGER NOT NULL, " +
                "tag INTEGER NOT NULL, " +
                "msg TEXT NOT NULL" +
                ")"

        suspend fun query(tag: Int, begin: Long, end: Long) = runCPU {
            val cursor = Store.db.rawQuery(
                "SELECT create_timestamp, msg FROM $TB_NAME " +
                        "WHERE create_timestamp >= ? " +
                        "AND create_timestamp < ? " +
                        "AND tag = ?", arrayOf(begin.toString(), end.toString(), tag.toString())
            )
            val list = ArrayList<StoreLog>()
            cursor.use {
                while (cursor.moveToNext()) {
                    list.add(
                        StoreLog(
                            cursor.getLong(0),
                            cursor.getString(1)
                        )
                    )
                }
            }
            list
        }
    }

}

suspend fun writeLog(tag: Int, msg: String) = runCPU {
    val now = currentTimestamp()
    Store.db.execSQL(
        "INSERT INTO ${StoreLog.TB_NAME} (create_timestamp, tag, msg) VALUES (?, ?, ?)",
        arrayOf(now, tag, msg)
    )
}

suspend fun writeError(msg: String) {
    writeLog(StoreLog.TAG_ERROR, msg)
}

suspend fun writeError(e: Exception) {
    writeError(e.message ?: stringById(R.string.t1733460848_310))
}















